<template>
  <div class="user-management">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" size="small" @click="fetchUsers">刷新数据</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-container">
        <el-input
          v-model="searchParams.account_name"
          placeholder="搜索用户昵称"
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-input
          v-model="searchParams.username"
          placeholder="搜索账号"
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-button type="primary" @click="searchUsers">搜索</el-button>
      </div>
      
      <!-- 用户列表表格 -->
      <el-table
        :data="userList"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
        :header-cell-style="{backgroundColor: '#f5f7fa', color: '#606266', fontWeight: 'bold'}"
        :cell-style="{textAlign: 'center'}"
        :header-cell-class-name="'text-center'"
      >
        <el-table-column prop="user_id" label="用户ID" width="100" align="center" />
        <el-table-column prop="account_name" label="用户昵称" min-width="120" align="center" />
        <el-table-column prop="username" label="账号" min-width="120" align="center" />
        <el-table-column prop="phone" label="联系电话" min-width="120" align="center" />

        <el-table-column prop="register_at" label="注册时间" min-width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.register_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="is_admin" label="用户类型" min-width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.is_admin ? 'danger' : 'info'">
              {{ scope.row.is_admin ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="100" align="center" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              :type="scope.row.life === 1 ? 'danger' : 'success'"
              @click="toggleUserLife(scope.row)"
            >
              {{ scope.row.life === 1 ? '禁用' : '解封' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="用户详情"
      width="500px"
    >
      <div v-if="currentUser" class="user-details">
        <div class="detail-item">
          <span class="label">用户ID：</span>
          <span>{{ currentUser.user_id }}</span>
        </div>
        <div class="detail-item">
          <span class="label">显示名称：</span>
          <span>{{ currentUser.account_name }}</span>
        </div>
        <div class="detail-item">
          <span class="label">登录账号：</span>
          <span>{{ currentUser.username }}</span>
        </div>
        <div class="detail-item">
          <span class="label">用户类型：</span>
          <el-tag :type="currentUser.is_admin ? 'danger' : 'info'">
            {{ currentUser.is_admin ? '管理员' : '普通用户' }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="label">联系电话：</span>
          <span>{{ currentUser.phone }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

const loading = ref(false)
const searchParams = ref({
  account_name: '',
  username: '',
  is_admin: 0  // 默认只显示非管理员用户
})
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userList = ref([])
const dialogVisible = ref(false)
const currentUser = ref(null)

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('请先登录')
      return
    }

    // 构建请求参数
    const params = {
      is_admin: searchParams.value.is_admin
    }

    // 只有当有值时才添加搜索参数
    if (searchParams.value.account_name) {
      params.account_name = searchParams.value.account_name
    }
    if (searchParams.value.username) {
      params.username = searchParams.value.username
    }

    console.log('Fetching users with params:', params)

    const response = await axios.get('http://127.0.0.1:5000/api/admin/users', {
      params,
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    console.log('Response:', response.data)

    // 检查响应状态
    if (Array.isArray(response.data)) {
      userList.value = response.data
    } else if (response.data.code === 200) {
      userList.value = response.data.data
    } else {
      ElMessage.error(response.data.msg || '获取用户列表失败')
    }

    console.log('Updated userList:', userList.value)
  } catch (error) {
    console.error('获取用户列表失败:', error)
    if (error.response?.status === 403) {
      ElMessage.error('没有权限访问此页面')
    } else if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
    } else {
      ElMessage.error('获取用户列表失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 搜索用户
const searchUsers = () => {
  fetchUsers()
}

// 查看用户详情
const viewUserDetails = async (userId) => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('请先登录')
      return
    }

    const response = await axios.get(`http://127.0.0.1:5000/api/admin/users/${userId}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.data.code === 200) {
      currentUser.value = response.data.data
      dialogVisible.value = true
    } else {
      ElMessage.error(response.data.msg || '获取用户详情失败')
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
    if (error.response?.status === 403) {
      ElMessage.error('没有权限访问此页面')
    } else if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
    } else if (error.response?.status === 404) {
      ElMessage.error('用户不存在')
    } else {
      ElMessage.error('获取用户详情失败，请稍后重试')
    }
  }
}

const toggleUserLife = async (user) => {
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.error('请先登录')
    return
  }

  const originalLife = user.life
  const newLife = originalLife === 1 ? 0 : 1

  const index = userList.value.findIndex(u => u.user_id === user.user_id)
  if (index === -1) {
    ElMessage.error('用户不存在')
    return
  }

  // 先本地更新，用 splice 替换元素，触发响应式更新
  userList.value.splice(index, 1, { ...user, life: newLife })

  try {
    const response = await axios.put(
      `http://127.0.0.1:5000/api/admin/users/${user.user_id}/life`,
      { life: newLife },
      {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }
    )

    if (response.data.status === 200) {
      ElMessage.success(`用户已${newLife === 1 ? '解封' : '禁用'}`)
      fetchUsers()
    } else {
      // 回滚
      userList.value.splice(index, 1, { ...user, life: originalLife })
      ElMessage.error(response.data.msg || '操作失败')
    }
  } catch (error) {
    console.error('修改用户状态失败:', error)
    // 回滚
    userList.value.splice(index, 1, { ...user, life: originalLife })
    ElMessage.error('操作失败，请稍后再试')
  }
}


// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsers()
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchUsers()
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.main-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
  flex-wrap: wrap;
}

.search-input {
  width: 250px;
  margin-right: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.user-details {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-item .label {
  width: 100px;
  color: #606266;
  font-weight: bold;
}

:deep(.text-center) {
  text-align: center !important;
}

:deep(.el-table .cell) {
  padding: 8px 12px;
  line-height: 1.5;
  word-break: break-all;
}

:deep(.el-table__header) {
  font-weight: bold;
}
</style>